package com.jefe.service.service.persistence;

import com.jefe.service.NoSuchMessageTblException;
import com.jefe.service.model.MessageTbl;
import com.jefe.service.model.impl.MessageTblImpl;
import com.jefe.service.model.impl.MessageTblModelImpl;

import com.liferay.portal.SystemException;
import com.liferay.portal.kernel.annotation.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistry;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class MessageTblPersistenceImpl extends BasePersistenceImpl
    implements MessageTblPersistence {
    public static final String FINDER_CLASS_NAME_ENTITY = MessageTblImpl.class.getName();
    public static final String FINDER_CLASS_NAME_LIST = FINDER_CLASS_NAME_ENTITY +
        ".List";
    public static final FinderPath FINDER_PATH_FIND_ALL = new FinderPath(MessageTblModelImpl.ENTITY_CACHE_ENABLED,
            MessageTblModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
            "findAll", new String[0]);
    public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(MessageTblModelImpl.ENTITY_CACHE_ENABLED,
            MessageTblModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
            "countAll", new String[0]);
    private static Log _log = LogFactoryUtil.getLog(MessageTblPersistenceImpl.class);
    @BeanReference(name = "com.jefe.service.service.persistence.MessageTblPersistence.impl")
    protected com.jefe.service.service.persistence.MessageTblPersistence messageTblPersistence;

    public void cacheResult(MessageTbl messageTbl) {
        EntityCacheUtil.putResult(MessageTblModelImpl.ENTITY_CACHE_ENABLED,
            MessageTblImpl.class, messageTbl.getPrimaryKey(), messageTbl);
    }

    public void cacheResult(List<MessageTbl> messageTbls) {
        for (MessageTbl messageTbl : messageTbls) {
            if (EntityCacheUtil.getResult(
                        MessageTblModelImpl.ENTITY_CACHE_ENABLED,
                        MessageTblImpl.class, messageTbl.getPrimaryKey(), this) == null) {
                cacheResult(messageTbl);
            }
        }
    }

    public void clearCache() {
        CacheRegistry.clear(MessageTblImpl.class.getName());
        EntityCacheUtil.clearCache(MessageTblImpl.class.getName());
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
    }

    public MessageTbl create(int id) {
        MessageTbl messageTbl = new MessageTblImpl();

        messageTbl.setNew(true);
        messageTbl.setPrimaryKey(id);

        return messageTbl;
    }

    public MessageTbl remove(int id)
        throws NoSuchMessageTblException, SystemException {
        Session session = null;

        try {
            session = openSession();

            MessageTbl messageTbl = (MessageTbl) session.get(MessageTblImpl.class,
                    new Integer(id));

            if (messageTbl == null) {
                if (_log.isWarnEnabled()) {
                    _log.warn("No MessageTbl exists with the primary key " +
                        id);
                }

                throw new NoSuchMessageTblException(
                    "No MessageTbl exists with the primary key " + id);
            }

            return remove(messageTbl);
        } catch (NoSuchMessageTblException nsee) {
            throw nsee;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    public MessageTbl remove(MessageTbl messageTbl) throws SystemException {
        for (ModelListener<MessageTbl> listener : listeners) {
            listener.onBeforeRemove(messageTbl);
        }

        messageTbl = removeImpl(messageTbl);

        for (ModelListener<MessageTbl> listener : listeners) {
            listener.onAfterRemove(messageTbl);
        }

        return messageTbl;
    }

    protected MessageTbl removeImpl(MessageTbl messageTbl)
        throws SystemException {
        Session session = null;

        try {
            session = openSession();

            if (messageTbl.isCachedModel() || BatchSessionUtil.isEnabled()) {
                Object staleObject = session.get(MessageTblImpl.class,
                        messageTbl.getPrimaryKeyObj());

                if (staleObject != null) {
                    session.evict(staleObject);
                }
            }

            session.delete(messageTbl);

            session.flush();
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

        EntityCacheUtil.removeResult(MessageTblModelImpl.ENTITY_CACHE_ENABLED,
            MessageTblImpl.class, messageTbl.getPrimaryKey());

        return messageTbl;
    }

    /**
     * @deprecated Use <code>update(MessageTbl messageTbl, boolean merge)</code>.
     */
    public MessageTbl update(MessageTbl messageTbl) throws SystemException {
        if (_log.isWarnEnabled()) {
            _log.warn(
                "Using the deprecated update(MessageTbl messageTbl) method. Use update(MessageTbl messageTbl, boolean merge) instead.");
        }

        return update(messageTbl, false);
    }

    /**
     * Add, update, or merge, the entity. This method also calls the model
     * listeners to trigger the proper events associated with adding, deleting,
     * or updating an entity.
     *
     * @param                messageTbl the entity to add, update, or merge
     * @param                merge boolean value for whether to merge the entity. The
     *                                default value is false. Setting merge to true is more
     *                                expensive and should only be true when messageTbl is
     *                                transient. See LEP-5473 for a detailed discussion of this
     *                                method.
     * @return                true if the portlet can be displayed via Ajax
     */
    public MessageTbl update(MessageTbl messageTbl, boolean merge)
        throws SystemException {
        boolean isNew = messageTbl.isNew();

        for (ModelListener<MessageTbl> listener : listeners) {
            if (isNew) {
                listener.onBeforeCreate(messageTbl);
            } else {
                listener.onBeforeUpdate(messageTbl);
            }
        }

        messageTbl = updateImpl(messageTbl, merge);

        for (ModelListener<MessageTbl> listener : listeners) {
            if (isNew) {
                listener.onAfterCreate(messageTbl);
            } else {
                listener.onAfterUpdate(messageTbl);
            }
        }

        return messageTbl;
    }

    public MessageTbl updateImpl(com.jefe.service.model.MessageTbl messageTbl,
        boolean merge) throws SystemException {
        Session session = null;

        try {
            session = openSession();

            BatchSessionUtil.update(session, messageTbl, merge);

            messageTbl.setNew(false);
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

        EntityCacheUtil.putResult(MessageTblModelImpl.ENTITY_CACHE_ENABLED,
            MessageTblImpl.class, messageTbl.getPrimaryKey(), messageTbl);

        return messageTbl;
    }

    public MessageTbl findByPrimaryKey(int id)
        throws NoSuchMessageTblException, SystemException {
        MessageTbl messageTbl = fetchByPrimaryKey(id);

        if (messageTbl == null) {
            if (_log.isWarnEnabled()) {
                _log.warn("No MessageTbl exists with the primary key " + id);
            }

            throw new NoSuchMessageTblException(
                "No MessageTbl exists with the primary key " + id);
        }

        return messageTbl;
    }

    public MessageTbl fetchByPrimaryKey(int id) throws SystemException {
        MessageTbl messageTbl = (MessageTbl) EntityCacheUtil.getResult(MessageTblModelImpl.ENTITY_CACHE_ENABLED,
                MessageTblImpl.class, id, this);

        if (messageTbl == null) {
            Session session = null;

            try {
                session = openSession();

                messageTbl = (MessageTbl) session.get(MessageTblImpl.class,
                        new Integer(id));
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (messageTbl != null) {
                    cacheResult(messageTbl);
                }

                closeSession(session);
            }
        }

        return messageTbl;
    }

    public List<Object> findWithDynamicQuery(DynamicQuery dynamicQuery)
        throws SystemException {
        Session session = null;

        try {
            session = openSession();

            dynamicQuery.compile(session);

            return dynamicQuery.list();
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    public List<Object> findWithDynamicQuery(DynamicQuery dynamicQuery,
        int start, int end) throws SystemException {
        Session session = null;

        try {
            session = openSession();

            dynamicQuery.setLimit(start, end);

            dynamicQuery.compile(session);

            return dynamicQuery.list();
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    public List<MessageTbl> findAll() throws SystemException {
        return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    public List<MessageTbl> findAll(int start, int end)
        throws SystemException {
        return findAll(start, end, null);
    }

    public List<MessageTbl> findAll(int start, int end, OrderByComparator obc)
        throws SystemException {
        Object[] finderArgs = new Object[] {
                String.valueOf(start), String.valueOf(end), String.valueOf(obc)
            };

        List<MessageTbl> list = (List<MessageTbl>) FinderCacheUtil.getResult(FINDER_PATH_FIND_ALL,
                finderArgs, this);

        if (list == null) {
            Session session = null;

            try {
                session = openSession();

                StringBuilder query = new StringBuilder();

                query.append("FROM com.jefe.service.model.MessageTbl ");

                if (obc != null) {
                    query.append("ORDER BY ");
                    query.append(obc.getOrderBy());
                }

                Query q = session.createQuery(query.toString());

                if (obc == null) {
                    list = (List<MessageTbl>) QueryUtil.list(q, getDialect(),
                            start, end, false);

                    Collections.sort(list);
                } else {
                    list = (List<MessageTbl>) QueryUtil.list(q, getDialect(),
                            start, end);
                }
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (list == null) {
                    list = new ArrayList<MessageTbl>();
                }

                cacheResult(list);

                FinderCacheUtil.putResult(FINDER_PATH_FIND_ALL, finderArgs, list);

                closeSession(session);
            }
        }

        return list;
    }

    public void removeAll() throws SystemException {
        for (MessageTbl messageTbl : findAll()) {
            remove(messageTbl);
        }
    }

    public int countAll() throws SystemException {
        Object[] finderArgs = new Object[0];

        Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
                finderArgs, this);

        if (count == null) {
            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(
                        "SELECT COUNT(*) FROM com.jefe.service.model.MessageTbl");

                count = (Long) q.uniqueResult();
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (count == null) {
                    count = Long.valueOf(0);
                }

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, finderArgs,
                    count);

                closeSession(session);
            }
        }

        return count.intValue();
    }

    public void afterPropertiesSet() {
        String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
                    com.liferay.util.service.ServiceProps.get(
                        "value.object.listener.com.jefe.service.model.MessageTbl")));

        if (listenerClassNames.length > 0) {
            try {
                List<ModelListener<MessageTbl>> listenersList = new ArrayList<ModelListener<MessageTbl>>();

                for (String listenerClassName : listenerClassNames) {
                    listenersList.add((ModelListener<MessageTbl>) Class.forName(
                            listenerClassName).newInstance());
                }

                listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
            } catch (Exception e) {
                _log.error(e);
            }
        }
    }
}
